package com.Cychat.chat.service.impl;


import com.Cychat.chat.service.ChatOssSevice;
import com.Cychat.commons.config.OssConfig;
import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Auther: 刘博文  <br/>
 * Date: 2025/10/31:14:05  <br/>
 * Description: 文件上传service实现类
 */
@Service
public class ChatOssSeviceImpl implements ChatOssSevice {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public String uploadimages(MultipartFile file, Long userId) throws IOException {
        try {
            // 指定文件夹路径，例如: avatars/用户ID/文件名
            String folderPath = "chat/" + userId + "/";

            // 生成唯一文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

            // 完整的对象键（包含文件夹路径）
            String objectName = folderPath + fileName;

            // 上传文件
            ossClient.putObject(ossConfig.getBucketName(), objectName, file.getInputStream());

            // 返回访问URL
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;
        } finally {
            // 注意：这里不再关闭ossClient，因为它现在是Spring管理的Bean
        }
    }
}
